﻿namespace IBTrader.Indicator.CandleStick
{
    using IBTrader.Modules.Read;
    using IBTrader.Charts;
    using System;

    internal abstract class Base : BasePrices, ILast
    {
        protected Item item;
        private readonly int interval;
        internal Base(Worker worker, ChartArgs chartArgs, int interval = 60, int pinterval = 20) : base(worker, chartArgs, pinterval) { this.interval = interval; }
        internal Base(Worker worker, int interval = 60, int pinterval = 20) : this(worker, new ChartArgs(), interval, pinterval) { }
        public override void Add(object sender, Line line)
        {
            if (item != null && item.OpenLine.DateTime.Ticks + (interval * TimeSpan.TicksPerSecond) < line.DateTime.Ticks)
            {
                Add(sender, item);
                item = null;
            }
            if (item == null) item = NewItem();
            item.Add(line);
        }
        protected virtual Item NewItem()
        {
            return new Item();
        }
        protected virtual void Add(object _, Item item)
        {
            OnHit(item);
        }

        #region ILast
        private Item last;
        Item ILast.Last
        {
            get { return last ?? item; }
        }
        protected override void OnHit(Line line, double price)
        {
            last = item;
            base.OnHit(line, price);
        }
        #endregion
    }
}
